//var log = log4javascript.getLogger("BACKGROUNDPAGE");
//var layout = new log4javascript.PatternLayout("%c %d{HH:mm:ss} %-5p - %m%n");
//var appender = new log4javascript.PopUpAppender();
//appender.setLayout(layout);
//log.addAppender(appender);

log.debug("logging...");

//var popupPort = chrome.extension.connect({name: "results"});


var tabs = [];
var portsMap = {};

//benutze Ports hier
//hier kommt der request von der popup seite rein. als Antwort sollte ein Array der passenden responses gesendet werden
//darin muessen auch die tab-ids enthalten sein, damit von der popup-seite in den tab gesprungen werden kann.
chrome.extension.onConnect.addListener(function(popupPort) {
    //chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    log.info("background.js : oncon : Connect... port.id: " + popupPort.id);

    //   log.debug(sender.tab ? "from a tab with the url:" + sender.tab.url : "from the extension");
    if (popupPort.name == "requestPort") {

        log.info("background.js : oncon : Connect on requestPort...");

        popupPort.onMessage.addListener(function(request) {

            if (request) {

            	log.debug("background.js : onmsg : request.query: " + request.query);

        		// ------------------------------------
				var realtime;
				if (localStorage == null) realtime= "-1";
				else if (localStorage.realtimesearch == null) realtime= "-1";
				else realtime = localStorage.realtimesearch;

				if (typeof realtime === "undefined") {
					log.debug("background.js : onmsg : realtimesearch: defaults to -1");
					realtime = "-1";
				}
				log.debug("background.js : onmsg : realtimesearch: " + realtime);
				log.debug("background.js : onmsg : request.incremental : " + request.incremental );

				if(typeof request.incremental !== "undefined" && request.incremental == true) {
					var rt = parseInt(realtime);

					log.debug("parseInt(realtime) : rt : " + rt)
					log.debug("request.query.length: " + request.query.length)

					if(rt<0) {
						return;
					} else if (rt>=0 && request.query.length<rt) {
						request.query = "";
					}
				}
				
				// ------------------------------------
				var highlight;
				if (localStorage == null) highlight = "pink";
				else if (localStorage.highlightcolor == null) highlight = "plum";
				else highlight = localStorage.highlightcolor;

				if (typeof highlight === "undefined") {
					log.debug("background.js : onmsg : highlight color was undefined");
					highlight = "yellow";
				}
				// log.debug("background.js : onmsg : highlight color is " + highlight);
                
                if (tabs.length == 0) {
                    // wie konnte das extension icon ohne zugehoerigen tab geklickt werden?
                    log.error("background.js : onmsg : No tabs found");
                    alert("No tabs found. Please open new tabs to search in!");
                } else {
                    log.debug("background.js : onmsg : found: " + tabs.length + " tabs.");
                }
                for (i = 0; i < tabs.length; i++) {

                    var tab = tabs[i];

                    log.debug("|||||||||||||||||||||||||||||||||tab: " + i + " |||||||||||||||||||||||||||||||||||||||||||");
                    log.debug("background.js : onmsg : connecting to tab[i:" + i + "] with id: " + tab.id);

                    var tabPort = chrome.tabs.connect(tab.id, null);
                    tabPort.name = tab.id;
                    log.debug("background.js : onmsg : tabPort.name: " + tabPort.name);

                    log.debug("background.js : onmsg : tabPort.postMessage...");
                    tabPort.postMessage({
                        query: request.query,
                        highlightcolor: highlight,
                        realtimesearch: realtime,
                        tab: tab
                    });
                    log.debug("background.js : onmsg : tabPort.postMessage...done");

                    tabPort.onMessage.addListener(function(data) {
                    	log.debug("background.js : onmsg : onMessage listener data: " + odump(data,1,1));

                        if (data.hitcount > 0) {
                            log.info("background.js : onmsg : Posting response to popupPort: " + popupPort.name);
                            popupPort.postMessage(data);
                        } else {
                            log.debug("background.js: no hits found");
                            popupPort.postMessage(data);
                        }
                    });
                }
            }
        });
    }
});

function openTabSearch() {
    log.debug("Opening smart search");
    openPopup(300, 500, chrome.extension.getURL('popup.html'));
}

//chrome.extension.onRequest.addListener(
//        function(request, sender, sendResponse) {
//            log.info(sender.tab ?
//                     "from a content script:" + sender.tab.url :
//                     "from the extension");
//            if (request.greeting == "popupOpened") {
////                registerAllTabs();
//                sendResponse({farewell: "registerAllTabs()"});
//            }
//            else {
//                sendResponse({}); // snub them.
//            }
//        });


// Register all opened tabs in the global tab list
//function registerAllTabs() {
//    try {
//
//        log.debug("start registerAllTabs()");
//
//        var someTabList = [];
//
//        // for that, first load a lost of all windows
//        chrome.windows.getAll({ populate: true }, function(windowList) {
//            try {
//
//                log.debug("start to poulate tab list");
//
//                // iterate throuh all windows, to reach all the tabs inside
//                for (var i = 0; i < windowList.length; i++) {
//
//                    //    		log.debug("someTabList of a window:" + odump(someTabList));
//                    someTabList = windowList[i].tabs;
//
//                    var addElement = true;
//
//                    // iterate the local, just loaded list
//                    for (var m = 0; m < someTabList.length; m++) {
//                        addElement = true;
//                        // iterate the global tabs list+
//                        for (var j = 0; j < tabs.length; j++) {
//                            // matching on the diagonal, then the element is present
//                            if (tabs[j].id == someTabList[m].id) {
//                                // remove element from fullTabList, so aftwerwards only the missing elements are inside
//                                // log.debug("someTabList.length" + someTabList.length);
//                                addElement = false;
//                                // log.debug("someTabList.length" + someTabList.length);
//                            }
//                        }
//
//                        //	         	log.debug("add the remaining someTabList to the global tabs" + odump(someTabList[m]));
//
//                        // Add the remaining tab, which is new to the global tab list
//                        if (addElement == true) tabs.push(someTabList[m]);
//
//                        //	         	log.debug("resulting global tab list: " + odump(tabs));
//
//                    }
//                }
//
//            } catch (err) {
//                log.error(err);
//            }
//        });
//
//        log.debug("registerAllTabs|----------------------------------------------+-+-+-+-----------------------------------------");
//        log.debug("resulting global tab list: " + odump(tabs));
//        log.debug("registerAllTabs|----------------------------------------------+-+-+-+-----------------------------------------");
//        log.debug("end registerAllTabs()");
//
//    } catch (err) {
//
//        log.error(err);
//
//    }
//}


function openPopup(width, height, url) {
    var w = width;
    var h = height;
    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2);

    if (window.settingsWin) {
        window.settingsWin.close();
        window.settingsWin = null;
    }

    window.settingsWin = window.open(url, url, 'width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
    window.settingsWin.focus();
}


chrome.extension.onConnect.addListener(function(port) {

    log.debug("a) port: connected: " + port.name);
    //    log.debug("port: " + odump(port));

    if (port.name == 'smartsearch') {


        port.onMessage.addListener(function(data) {
            if (data.command == "openSmartSearch")
                openTabSearch();
        });
    }
});

chrome.extension.onConnect.addListener(function(port) {

    log.debug("b) port: connected: " + port.name);


    if (port.name != 'smartsearch' && data.query != null)

        log.debug("!smartsearch -> port: connected");

    port.onMessage.addListener(function(data) {
        log.debug("onMessage listener data: " + odump(data));
    });
});

chrome.tabs.onCreated.addListener(function(tab) {
    log.info('tabs.onCreated --'
            + ' window: ' + tab.windowId
            + ' tab: ' + tab.id
            + ' index: ' + tab.index
            + ' url: ' + tab.url);

    tabs.push(tab);
    //
    //    for (var i = 0; i < tabs.length; i++) {
    //        log.info('nach push: tabs:' + tabs[i].id);
    //    }
});


//TODO: remove implementieren

chrome.tabs.onRemoved.addListener(function(tabId) {

    log.debug('tabs.onRemoved tab.id: ' + tabId);

    //    for (var i = 0; i < tabs.length; i++) {
    //        log.info('vorher: tabs:' + tabs[i].id);
    //    }

    removeById(tabId, tabs);

    //    for (i = 0; i < tabs.length; i++) {
    //        log.info('nachher: tabs:' + tabs[i].id);
    //    }
});

function removeById(tabId, array) {

    for (var i = 0; i < array.length; i++) {

        //        log.debug(i + ": array[i].id: " + array[i].id + " tabId: " + tabId);

        if (array[i].id == tabId) {

            //            log.debug(i + ": remove tabId: " + tabId);

            array.splice(i, 1);
            //            log.debug("removed tab ");
        }
    }

    //    for (var i = 0; i < array.length; i++) {
    //        log.info('removeById: tabs:' + array[i].id);
    //    }
}
